package com.xxl.job.executor.service;

import com.mashape.unirest.http.Headers;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.xxl.job.executor.utils.SpringContextUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;

import java.util.List;

public class SimbaToken {
    public static String token;
    public static void Login() throws UnirestException{

        Environment environment = (Environment) SpringContextUtil.getBean("environment");
        String url = environment.getProperty("simba.login.url");
        String authKey = environment.getProperty("ipass.authKey");
        HttpResponse<JsonNode> response = Unirest.post(url)
                .header("authKey", authKey)
                .asJson();
        JsonNode body = response.getBody();
        if (body != null && body.getObject().get("code").equals(0)) {
            Headers header = response.getHeaders();
            String setCookie = header.get("set-cookie").get(0);
            token = "Bearer " + setCookie.substring(0, setCookie.indexOf(";")).replace("access_token_obj=", "");
        }
    }

    public static String getToken() throws UnirestException {
        return token;
    }
}
